package com.easy.controller;

import com.easy.bean.GiveBean;
import com.easy.service.GiveService;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/give")
public class GiveController {
    @Autowired
    private GiveService giveService;

    @PostMapping("/toggle")
    public Result toggleGive(@RequestBody GiveBean give) {
        try {
            // 检查是否已经点赞
            boolean isLiked = giveService.checkIfLiked(give.getUserId(), give.getPostId());

            if (isLiked) {
                // 如果已经点赞，取消点赞
                int result = giveService.cancelGive(give.getUserId(), give.getPostId());
                return result > 0 ? Result.success("取消点赞成功", false) : Result.fail(500, "取消点赞失败");
            } else {
                // 如果没有点赞，添加点赞
                int result = giveService.add(give);
                return result > 0 ? Result.success("点赞成功", true) : Result.fail(500, "点赞失败");
            }
        } catch (Exception e) {
            return Result.fail(500, "操作失败: " + e.getMessage());
        }
    }

    @GetMapping("/check/{userId}/{postId}")
    public Result checkLikeStatus(@PathVariable("userId") Integer userId,
                                  @PathVariable("postId") Integer postId) {
        try {
            boolean isLiked = giveService.checkIfLiked(userId, postId);
            return Result.success( isLiked);
        } catch (Exception e) {
            return Result.fail(500, "查询失败");
        }
    }

    @GetMapping("/count/{postId}")
    public Result getLikeCount(@PathVariable("postId") Integer postId) {
        try {
            int count = giveService.getLikeCount(postId);
            return Result.success( count);
        } catch (Exception e) {
            return Result.fail(500, "查询失败");
        }
    }
}